package mianyang.zhangsan.com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mianyang.zhangsan.com.mapper.NoticeMapper;
import mianyang.zhangsan.com.pojo.Notice;
import mianyang.zhangsan.com.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.List;

@Service("noticeService")
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 分页查询所有的新闻信息
     * @param pageNo
     * @return
     */
    @Override
    public Page<Notice> queryPage(int pageNo) {

        return noticeMapper.selectPage(new Page<>(pageNo, 3), null);
    }

    /**
     * 添加一条新闻
     * @param notice
     */
    @Override
    public void addNotice(Notice notice) {
        noticeMapper.insert(notice);
    }

    /**
     * 根据查询条件分页查询新闻
     * @param page
     * @param rows
     * @param notice
     * @return
     */
    @Override
    public Page<Notice> queryPageWrapper(int page, int rows, Notice notice) {
        QueryWrapper<Notice> wrapper = queryWrapper(notice);
        return noticeMapper.selectPage(new Page<>(page, rows), wrapper);
    }

    /**
     * 删除一个notice
     * @param noticeId
     */
    @Override
    public void delete(int noticeId) {
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
        wrapper.eq("noticeid", noticeId);
        noticeMapper.delete(wrapper);
    }

    /**
     * 删除多个notice
     * @param noticeIds
     */
    @Override
    public void deletes(String noticeIds) {
        String[] notices = noticeIds.split(",");
        for (String notice:notices){
            delete(Integer.parseInt(notice));
        }
    }

    /**
     * 根据id更新notice
     * @param noticeId
     * @param notice
     */
    @Override
    public void updateNotice(int noticeId, Notice notice) {
        QueryWrapper<Notice> wrapper  = new QueryWrapper<>();
        wrapper.eq("noticeid", noticeId);
        noticeMapper.update(notice, wrapper);
    }

    @Override
    public List<Notice> queryListByWrapper(Notice notice) {
        QueryWrapper<Notice> wrapper = queryWrapper(notice);
        return noticeMapper.selectList(wrapper);
    }

    @Override
    public QueryWrapper<Notice> queryWrapper(Notice notice) {
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
        if (notice.getTitle() != null && !"".equals(notice.getTitle())){
            wrapper.like("title", notice.getTitle());
        }
        if (notice.getPublishDate() != null && !"".equals(notice.getPublishDate())){
            wrapper.lt("publishdate", notice.getPublishDate());
        }
        return wrapper;
    }
}
